package com.example.demo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.demo.Common.CommonIT;
import com.example.demo.Common.MD5Util;
import com.example.demo.Excel.ExcelUtils;
import com.example.demo.annotation.AuthToken;
import com.example.demo.entity.User;
import com.example.demo.kit.ConstantKit;
import com.example.demo.kit.Md5TokenGenerator;
import com.example.demo.service.IUserService;
import com.xc.roadRisk.common.utils.ResponseUtils;
import com.xc.roadRisk.common.vo.PageList;
import com.xc.roadRisk.common.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hanfei
 * @since 2020-04-08
 */
@Api(value = "用户",tags = "用户")
@RestController
public class UserController {
    @Autowired
    private IUserService userApi;
    @Autowired
    Md5TokenGenerator tokenGenerator;
    @ApiOperation("创建单个User")
    @ApiImplicitParam(name = "version", paramType = "path")
    @PostMapping("pv/users")
    @AuthToken
    public Response<Boolean> insert(@RequestBody User user) {
        Response response=new Response();
        if(userApi.findByUsername(user.getUser_name())!=null){
            response.setMsg("该用户已存在");
            response.setCode("500");
            return response;
        }
        MD5Util md5Util = new MD5Util();
        user.setPassword(md5Util.getMD5(user.getPassword()));
        CommonIT commonIT=new CommonIT();
        String id=commonIT.findId();
        user.setUser_id(id);
        response=ResponseUtils.returnObjectSuccess(userApi.insert(user));
        response.setMsg(id);


        return response;
    }
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    public Response login(@RequestParam(value = "username") String username,
                          @RequestParam(value = "password") String password){
        Response response=new Response();
        if(password!=null){
            MD5Util md5Util=new MD5Util();
            password=md5Util.getMD5(password);
        }
        if(userApi.findByUsername(username)==null){
            response.setCode("500");
            response.setMsg("账号不存在");
        }else if(userApi.login(username, password)==null){
            response.setCode("500");
            response.setMsg("密码错误");
        }else {
            User tdUser=userApi.login(username, password);
            response.setCode("200");
            response.setMsg("登录成功");
            response.setData(tdUser);
            Jedis jedis = new Jedis("localhost", 6379);
            String token = tokenGenerator.generate(username, password);
            jedis.set(username, token);
            jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME);
            jedis.set(token, username);
            jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
            Long currentTime = System.currentTimeMillis();
            jedis.set(token + username, currentTime.toString());
            //用完关闭
            jedis.close();
            response.setToken(token);
        }

        return response;
    }
    @ApiOperation("编辑单个User")
    @ApiImplicitParam(name = "version", paramType = "path")
    @PutMapping("pv/users/{uid}")
    @AuthToken
    public Response<Boolean> updateById(@PathVariable("uid") String uid, @RequestBody User user) {
        user.setUser_id(uid);
        CommonIT commonIT=new CommonIT();
        if(user.getPassword()!=null){
            MD5Util md5Util = new MD5Util();
            user.setPassword(md5Util.getMD5(user.getPassword()));
        }
        return ResponseUtils.returnObjectSuccess(userApi.updateById(user));
    }
    @ApiOperation("查询单个User")
    @ApiImplicitParam(name = "version", paramType = "path")
    @GetMapping("pb/users/{uid}")
    @AuthToken
    public Response<User> selectById(@PathVariable("uid") String uid) {
        return ResponseUtils.returnObjectSuccess(userApi.selectById(uid));
    }

    @ApiOperation("查询分页User")
    @ApiImplicitParam(name = "version", paramType = "path")
    @GetMapping("pb/users/action/search")
    @AuthToken
    public Response<PageList<User>> selectPage(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                               User user) {
        Page<User> page = userApi.selectPage(new Page<>(pageNo, pageSize), new EntityWrapper<>(user));
        return ResponseUtils.returnObjectSuccess(new PageList<>(page));
    }
    @ApiOperation("模糊查询分页")
    @ApiImplicitParam(name = "version", paramType = "path")
    @GetMapping("pb/users/action/findByKey")
    @AuthToken
    public Response<PageList<User>> findByKey(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                              @RequestParam(value = "key", required = false) String key) {
        Page<User> page = userApi.findByKey(new Page<>(pageNo, pageSize), key);
        return ResponseUtils.returnObjectSuccess(new PageList<>(page));
    }

    @ApiOperation("查询所有")
    @ApiImplicitParam(name = "version", paramType = "path")
    @GetMapping("pb/users/findall")
    @AuthToken
    public Response<List<User>> findall(User user) {
        return ResponseUtils.returnObjectSuccess(userApi.selectList(new EntityWrapper<>(user)));
    }

    @ApiOperation("导出")
    @GetMapping("/users/export")
    @AuthToken
    public String exportAll(HttpServletResponse response,User user) {
        List<User> list=userApi.selectList(new EntityWrapper<>(user));
        ExcelUtils.writeExcel(response,list,User.class);
        return null;
    }
    @ApiOperation("导入")
    @PostMapping("/users/import")
    @AuthToken
    public Response importAll(@RequestParam("file")MultipartFile file){
        List<User> list=ExcelUtils.readExcel(null,User.class,file);
        for(User a:list){
            CommonIT commonIT=new CommonIT();
            String id=commonIT.findId();
            a.setUser_id(id);
        }

        return ResponseUtils.returnObjectSuccess(userApi.insertBatch(list));
    }
    @ApiOperation("模糊查询加定向查询分页")
    @ApiImplicitParam(name = "version", paramType = "path")
    @GetMapping("pb/users/action/findByKeyAndAll")
    @AuthToken
    public Response<PageList<User>> findByKeyAndAll(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                    @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                                    @RequestParam(value = "key",required = false) String key,
                                                    User entity) {
        Page<User> page = userApi.findByKeyAndAll(new Page<>(pageNo, pageSize), key,entity);
        return ResponseUtils.returnObjectSuccess(new PageList<>(page));
    }
}
